from flask import Flask, request, jsonify, abort
import pymongo, json
import music163_search
from ..common.Token import generate_token
from ..base import base

client = pymongo.MongoClient(host='127.0.0.1', port=27017)
db = client.realtime


@base.route("/music/<string:title>", methods=['POST', 'GET'])
def search_music(title):
    # rev = request.get_json()['title']
    result_list = []
    collections = db.musicdb
    res = {}
    if title == "":
        abort()
        return
    results = collections.find({"title": {"$regex": title, "$options": "i"}}, {"_id": 0})
    for result in results:
        # print(result)
        collections = db.copyrightdb
        results = collections.find({"title": {"$regex": title, "$options": "i"}}, {"_id": 0})
        for result in results:
            # print(result)
            result_list.append(result)
        # code = {"code": 200}
        # result_list.append(code)
        res = result_list
        # result_list[0] = "code":"200"
        return jsonify(res)
    res = music163_search.search(title)
    # result_list = music163_search.search(title)
    # code = {"code": 200}
    # result_list.append(code)
    # results['code'] = '200'
    return jsonify(res)


@base.after_request
def after(res):
    url = request.path  # 读取到当前接口的地址
    data = {
        'code': 20000,
        'datas': res.get_json(),
        'message': '成功'
    }
    res.data = json.dumps(data).encode()

    # else:
    #     res.headers['Authorization'] = generate_token()
    # return 响应体, 状态码, 响应头
    return res
